﻿using System;
using System.IO;
using System.Text;
using UnityEngine;
using System.Collections.Generic;
using System.Collections;

public static class FileTool
{

    #region 读写文件
    private static FileStream stream;
	//读文本
	public static string ReadFile (string filePath)
	{
		try {
			string result = File.ReadAllText (filePath);
			return result;
		} catch (Exception e) {
			Debug.LogError ("读取文件失败:" + e.ToString ());
			return "";
		}
	}

	/// <summary>
	/// 将字节数组读成字符串
	/// </summary>
	/// <param name="bytes">Bytes.</param>
    public static string ReadFile(byte[] bytes)
    {
		return Encoding.UTF8.GetString (bytes);
	}

	/// <summary>
	/// 写入文件
	/// </summary>
	/// <param name="filePath">File path.</param>
	/// <param name="content">Content.</param>
	public static void WriteFile (string filePath, string content)
	{
        string dirPath = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(dirPath))
            Directory.CreateDirectory(dirPath);

		RemoveFile (filePath);

		if (!File.Exists (filePath)) {
			File.Create (filePath).Dispose ();
		}
		try {
			stream = File.OpenWrite (filePath);
			stream.SetLength (0);
			byte[] target = Encoding.UTF8.GetBytes (content);
			stream.Write (target, 0, target.Length);
			stream.Close ();
			stream.Dispose ();
		} catch (Exception e) {
			Debug.LogError ("写入文件错误:" + e.ToString ());
		}
	}

    /// <summary>
    /// 写入文件
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="bytes"></param>
    public static void WriteFile(string filePath,byte[] bytes)
    {
        string dirPath = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(dirPath))
            Directory.CreateDirectory(dirPath);

        RemoveFile(filePath);
        
        if (!File.Exists(filePath))
        {
            File.Create(filePath).Dispose();
        }
        try
        {
            stream = File.OpenWrite(filePath);
            stream.SetLength(0);
            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
            stream.Dispose();
        }
        catch (Exception e)
        {
            Debug.LogError("写入文件错误:" + e.ToString());
        }
    }

	//清理文件
	public static void RemoveFile (string filePath)
	{
		if (File.Exists (filePath)) {
			File.Delete (filePath);
		}
	}

    #endregion


    #region 文件及文件夹字符操作

    /// <summary>
	/// 获取文件的后缀名
	/// </summary>
	/// <returns>The file extension.</returns>
	public static string GetFileExtension(string filePath){
		return Path.GetExtension (filePath);
	}

	/// <summary>
	/// 获取没有后缀的文件名
	/// </summary>
	/// <returns>The file with out extension.</returns>
	public static string GetFileWithOutExtension(string filePath){
		return Path.GetFileNameWithoutExtension (filePath);
	}

	/// <summary>
	/// 获取文件的名字
	/// </summary>
	/// <returns>The file name.</returns>
	/// <param name="filePath">File path.</param>
	public static String GetFileName(string filePath)
	{
		return Path.GetFileNameWithoutExtension (filePath);
	}

    /// <summary>
    /// 获取文件夹的名字
    /// </summary>
    /// <returns></returns>
    public static string GetDirectoryName(string dirName)
    {
        dirName = dirName.FormatPath();
        if (Directory.Exists(dirName))
        {
            DirectoryInfo info = new DirectoryInfo(dirName);
            return info.Name;
        }
        return "";
    }


    #endregion


    #region 功能方法
    /// <summary>
	/// 递归拿到该目录中所有的文件   ignoreExtension忽略的文件后缀
	/// </summary>
	/// <param name="path"></param>
	/// <returns></returns>
	public static List<string> GetAllFile(string path,List<string> ignoreExtension = null)
	{
		List<string> result = new List<string>();
		path = PathTool.FormationPath(path);

		if (Directory.Exists(path))
		{
			string[] fileArray = Directory.GetFiles(path);
			List<string> fileList = new List<string> (fileArray);

			if (ignoreExtension != null && ignoreExtension.Count > 0) {
				for (int i = fileList.Count - 1;i >= 0; i--) {
					string fExt = FileTool.GetFileExtension (fileList [i]);
					if (ignoreExtension.IndexOf (fExt) > -1) {
						fileList.RemoveAt (i);
					}
				}
			}

			result.AddRange(new List<string>(fileList));

			string[] dirList = Directory.GetDirectories(path);
			foreach (string dir in dirList)
			{
				result.AddRange(GetAllFile(dir,ignoreExtension));
			}
		}
		return result;
	}

	/// <summary>
	/// 获取文件的MD5值
	/// </summary>
	/// <param name="fileName"></param>
	/// <returns></returns>
	public static string GetMD5HashFromFile(string fileName)
	{
		try
		{
			FileStream file = new FileStream(fileName, FileMode.Open);
			System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
			byte[] retVal = md5.ComputeHash(file);
			file.Close();

			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < retVal.Length; i++)
			{
				sb.Append(retVal[i].ToString("x2"));
			}
			return sb.ToString();
		}
		catch (Exception ex)
		{
			throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
		}
	}


	/// <summary>
	/// 选择某个目录
	/// </summary>
	/// <param name="fileFullName">File full name.</param>
	public static void OpenFolderAndSelectFile(String fileFullName)
	{
		System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
		psi.Arguments = "/e,/select," + fileFullName;
		System.Diagnostics.Process.Start(psi);
	}

	/// <summary>
	/// 两个参数都是目录,将 from目录中的所有文件移动到to目录
	/// </summary>
	/// <param name="srcPath">srcPath.</param>
	/// <param name="destPath">destPath.</param>
	public static void CopyDirectory(string srcPath, string destPath)
	{
		if(!Directory.Exists(srcPath) || !Directory.Exists(destPath))
		{
			return;
		}
	　　try
		{
　　　　		DirectoryInfo dir = new DirectoryInfo(srcPath);
	　　　　	FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下（不包含子目录）的文件和子目录
	　　　 	foreach (FileSystemInfo i in fileinfo)
			{
				if (i is DirectoryInfo)     //判断是否文件夹
				{
					if (!Directory.Exists(destPath+"\\"+i.Name))
					{
						Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
					}
					CopyDirectory(i.FullName, destPath + "\\" + i.Name);    //递归调用复制子文件夹
				}
				else
				{
					File.Copy(i.FullName, destPath + "\\" + i.Name,true);      //不是文件夹即复制文件，true表示可以覆盖同名文件
				}
			}
		}
		catch (Exception e)
		{
			throw e;
		}
	}

	/// <summary>
	/// 清理该文件夹的所有文件 
	/// </summary>
	/// <param name="path">Path.</param>
	public static void ClearDirectory(string path){
		path = PathTool.FormationPath (path);
		if (Directory.Exists (path)) {
			string[] allFiles = Directory.GetFiles (path,"*",SearchOption.AllDirectories);
			for (int i = 0; i < allFiles.Length; i++) {
				File.Delete (allFiles[i]);
			}
		}
	}

    public static void ChangeFileName(string filePath,string newName)
    {
        filePath = PathTool.FormationPath(filePath);
        if (!File.Exists(filePath))
        {
            Debug.LogError("改名失败" + filePath + " to " + newName);
            return;
        }

        string ext = GetFileExtension(filePath);

        string dirPath = Path.GetDirectoryName(filePath);

        string desPath = dirPath + "/" + newName + ext;

        if (File.Exists(desPath))
        {
            File.Delete(desPath);
        }

        desPath = PathTool.FormationPath(desPath);

        File.Move(filePath,desPath);
    }

    #endregion

}

